<template>
    <el-dialog :model-value="menuTreeVisible" :title="title" width="50%" @close="handleClose" align-center center>

        <div class="container">
            <el-scrollbar>
                <el-tree :props="treeProps" ref="treeRef" node-key="id" default-expand-all :data="treeData"
                    show-checkbox />
            </el-scrollbar>
        </div>

        <template #footer class="footer">
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleConfirm">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus'
import { getMenuTreeAPI, getRoleMenuAPI, updateRoleMenuAPI } from '@/api';

const emits = defineEmits(['update:modelValue', 'initRolrList'])

const props = defineProps({
    id: {
        type: Number,
        default: -1
    },
    title: {
        type: String,
        default: "标题"
    },
    menuTreeVisible: {
        type: Boolean,
        default: false
    }
})

const treeProps = {
    children: 'children',
    label: 'menuName',
}

const treeRef = ref(null)

const treeData = ref([])

const initgetTreeData = async (val) => {
    let res = await getMenuTreeAPI()
    treeData.value = res
    let rus = await getRoleMenuAPI(val)
    treeRef.value.setCheckedKeys(rus)
}

const handleClose = () => {
    emits('update:modelValue', false)
}

const handleConfirm = async () => {
    let menuIds = reactive([])
    menuIds = treeRef.value.getCheckedKeys();
    await updateRoleMenuAPI(props.id, menuIds)
    ElMessage.success("更改成功")
    emits('initRolrList')
    handleClose()
}

watch(
    () => props.menuTreeVisible,
    () => {
        let id = props.id
        console.log("---++", id)
        if (id != -1) {
            initgetTreeData(id)
        }
    }, { deep: true, immediate: true })


</script>

<style lang="scss" scoped>
.container {
    margin: 20px 0;
}

.el-dialog {
    margin: 20px;
}
</style>